package service;

import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;

import dao.HistoryDao;
import dao.IHistoryDao;
import po.EmpHistory;
import po.Employment;
import po.Rating;
import po.User;

public class HistoryService implements IHistoryService{
	private IHistoryDao historyDao;
	
	private List<EmpHistory> list;
	private Map<String, Object> request, session;
	
	public void setHistoryDao(IHistoryDao historyDao) {
		this.historyDao = historyDao;
	}
	
	public List getAllHistory(int id) {
		String hql = "from EmpHistory as his where costomerID="+id;
		list = historyDao.findByHql(hql);	
		return list;
	}
	
	public User getTutorByHisID(int id) {
		EmpHistory his = (EmpHistory)historyDao.findHisInfo(id);
		int userID = his.getTutorID();
		User user = (User)historyDao.findUserInfo(userID);
		return user;
	}
	
	public EmpHistory getHisByID(int id) {
		EmpHistory his = (EmpHistory)historyDao.findHisInfo(id);
		return his;
	}
	//flag=1 此时需要更新评分
	public boolean update(int id,String appraise,String mark,int flag) {	
		if(flag==1) {
			int rating = Integer.parseInt(mark);
			EmpHistory his = (EmpHistory)historyDao.findHisInfo(id);
			his.setAppraise(appraise);
			his.setMark(rating);
			//更新状态-已评价
			his.setStatus("1");
			User user = getUserByHisID(id);
			Rating rat = user.getRat();
			//更新数量
			int number = rat.getNumber();
			rat.setNumber(number+1);
			//更新好差评
			if(rating>5) {
				int good = rat.getGoodMark();
				rat.setGoodMark(good+1);
			}else {
				int bad = rat.getBadMark();
				rat.setBadMark(bad+1);
			}
			//更新平均分
			double avg = rat.getAvgMark();
			double sum = avg*number + rating;
			double newAvg = sum / (number+1);
			rat.setAvgMark(newAvg);
			
			historyDao.updateHistory(his);
			historyDao.updateRating(rat);
			
		}else {
			//第二次修改评价内容
			EmpHistory his = (EmpHistory)historyDao.findHisInfo(id);
			his.setAppraise(appraise);
			historyDao.updateHistory(his);
			
		}
		return true;
	}

	@Override
	public User getUserByHisID(int id) {
		// TODO Auto-generated method stub
		EmpHistory his = (EmpHistory)historyDao.findHisInfo(id);
		int userID = his.getCostomerID();
		User user = (User)historyDao.findUserInfo(userID);
		return user;
	}
}
